package com.itmuch.contentcenter.rocketmq;

import com.itmuch.contentcenter.dao.messaging.RocketmqTransactionLogMapper;
import com.itmuch.contentcenter.domain.dto.content.ShareAuditDto;
import com.itmuch.contentcenter.domain.entity.messaging.RocketmqTransactionLog;
import com.itmuch.contentcenter.service.content.ShareService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

/**
 * @author caiqian
 * @date 2021/5/10 10:35
 */
@RocketMQTransactionListener(txProducerGroup = "tx-add-bonus-group")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AddBounsTransactionListener implements RocketMQLocalTransactionListener {

  private final ShareService shareService;
  private final RocketmqTransactionLogMapper rocketmqTransactionLogMapper;

  @Override
  public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
    MessageHeaders headers = message.getHeaders();
    String transcationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);
    Integer shareId = Integer.valueOf((String) Objects.requireNonNull(headers.get("share_id")));

    try {
      this.shareService.auditByIdInDbWithRockMqLog(shareId, (ShareAuditDto) o, transcationId);
      return RocketMQLocalTransactionState.COMMIT;
    } catch (Exception e) {
      e.printStackTrace();
      return RocketMQLocalTransactionState.ROLLBACK;
    }
  }

  @Override
  public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
    MessageHeaders headers = message.getHeaders();
    String transcationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);

    RocketmqTransactionLog transactionLog = this.rocketmqTransactionLogMapper.selectOne(
        RocketmqTransactionLog.builder()
            .transactionId(transcationId)
            .build()
    );

    if (transactionLog != null) {
      return RocketMQLocalTransactionState.COMMIT;
    }

    return RocketMQLocalTransactionState.COMMIT;
  }
}
